package cn.itcast.n4_共享模型_管程;

import java.util.ArrayList;

public class Test05_线程安全分析_演示成员变量线程安全问题 {

    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 2000;

    public static void main(String[] args) {
        ThreadUnsafe test = new ThreadUnsafe();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                test.method1(LOOP_NUMBER);
            }, "Thread" + (i + 1)).start();
        }
    }
}

/**
 * 不安全的
 */
class ThreadUnsafe {
    /** 此时为成员变量 */
    ArrayList<String> list = new ArrayList<>();
    public void method1(int loopNumber) {
        for (int i = 0; i < loopNumber; i++) {
            method2();
            method3();
        }
    }
    private void method2() {
        list.add("1");
    }
    private void method3() {
        list.remove(0);
    }
}


